package com.ayoka.parenting.ui.group.topic.detail;

import android.app.Activity;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;

import com.ayoka.parenting.R;
import com.ayoka.parenting.adapter.TopicCommentAdapter;
import com.ayoka.parenting.bean.BasicUserInfoBean;
import com.ayoka.parenting.bean.CommentBean;
import com.ayoka.parenting.bean.PagerBean;
import com.ayoka.parenting.bean.TopicBean;
import com.ayoka.parenting.databinding.ActivityTopicDetailBinding;
import com.ayoka.parenting.databinding.HeaderTopicDetailBinding;
import com.ayoka.parenting.interf.SimpleTextWatchListener;
import com.ayoka.parenting.mvp.MVPBaseRecyclerViewActivity;
import com.jincp.common.brvah.BaseQuickAdapter;
import com.jincp.common.brvah.BaseViewHolder;
import com.jincp.common.brvah.RecycleViewDivider;
import com.jincp.common.model.ToolBarOptions;
import com.jincp.common.utils.TDevice;
import com.jincp.common.utils.UIUtils;

import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;

/**
 * @ProjectName: MVPPlugin.
 * @ClassName: TopicDetailActivity.
 * @Description: .
 * @Author: jincp.
 * @CreateDate: 2019/10/10 18:17.
 */
public class TopicDetailActivity extends MVPBaseRecyclerViewActivity<CommentBean, ActivityTopicDetailBinding, TopicDetailContract.View, TopicDetailPresenter> implements TopicDetailContract.View {

    public static void start(Activity activity, String circleGroupOwnerId, TopicBean topicBean) {
        Intent intent = new Intent(activity, TopicDetailActivity.class);
        intent.putExtra("CircleGroupOwnerId", circleGroupOwnerId);
        intent.putExtra("TopicBean", topicBean);
        activity.startActivity(intent);
    }

    private String circleGroupOwnerId;
    private TopicBean topicBean;

    private HeaderTopicDetailBinding headerBinding;

    private BasicUserInfoBean replyToUser;
    private String replyToTopicID;

    @Override
    protected void configIntentValue() {
        Intent intent = getIntent();
        if (intent != null) {
            circleGroupOwnerId = intent.getStringExtra("CircleGroupOwnerId");
            topicBean = (TopicBean) intent.getSerializableExtra("TopicBean");
        }
    }

    @Override
    protected int getContentLayout() {
        return R.layout.activity_topic_detail;
    }

    @Override
    protected void initViews() {
        super.initViews();
        headerBinding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.header_topic_detail, null, false);
        adapter.addHeaderView(headerBinding.getRoot());
        adapter.setHeaderAndEmpty(true);

        mDataBinding.edtContent.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, final boolean hasFocus) {
                UIUtils.postTaskDelay(new Runnable() {
                    @Override
                    public void run() {
                        if (hasFocus) {
                            if (replyToUser == null) {
                                mDataBinding.edtContent.setHint("期待你的精彩评论...");
                            } else {
                                mDataBinding.edtContent.setHint("回复" + replyToUser.WeixinNickName + "：");
                            }
                        } else {
                            replyToUser = null;
                            mDataBinding.edtContent.setHint("期待你的精彩评论...");
                        }
                    }
                }, 200);
            }
        });
        mDataBinding.edtContent.addTextChangedListener(new SimpleTextWatchListener() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() != 0) {
                    mDataBinding.btnSend.setEnabled(true);
                    mDataBinding.btnSend.setVisibility(View.VISIBLE);
                } else {
                    mDataBinding.btnSend.setEnabled(false);
                    mDataBinding.btnSend.setVisibility(View.GONE);
                }
            }
        });
        mDataBinding.btnSend.setOnClickListener(this);
    }

    @Override
    protected SwipeRefreshLayout getRefreshLayout() {
        return mDataBinding.swipeRefresh;
    }

    @Override
    protected RecyclerView getRecyclerView() {
        return mDataBinding.recyclerView;
    }

    @NonNull
    @Override
    protected BaseQuickAdapter<CommentBean, BaseViewHolder> getAdapter() {
        TopicCommentAdapter adapter = new TopicCommentAdapter(circleGroupOwnerId);
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                CommentBean comment = (CommentBean) adapter.getData().get(position);
                // 回复评论
                if (view.getId() == R.id.tv_comment) {
                    replyToUser = comment.UserInfo;
                    replyToTopicID = comment.Id;
                    TDevice.showSoftKeyboard(view);
                    mDataBinding.edtContent.requestFocus();
                }
                if (mPresenter != null) {
                    // 设置评论点赞
                    if (view.getId() == R.id.tv_praise) {
                        if (comment.IsLike == 0) {
                            mPresenter.praiseComment(comment.Id, position);
                        } else if (comment.IsLike == 1) {
                            mPresenter.cancelPraiseComment(comment.Id, position);
                        }
                    }
                    // 设置精彩评论
                    if (view.getId() == R.id.tv_star) {
                        if (comment.IsGood == 0) {
                            mPresenter.starComment(comment.Id, position);
                        } else if (comment.IsGood == 1) {
                            mPresenter.cancelStarComment(comment.Id, position);
                        }
                    }
                }
            }
        });
        return adapter;
    }

    @Override
    protected RecyclerView.ItemDecoration getRecycleDivider() {
        return new RecycleViewDivider.Builder(this)
                .setStyle(RecycleViewDivider.Style.BETWEEN)
                .setColor(UIUtils.getColor(R.color.white_f7))
                .setSize(5)
                .build();
    }

    @Override
    protected void getData(boolean isShowWaitDialog) {
        if (topicBean != null && mPresenter != null) {
            mPresenter.getTopicCommentListData(isShowWaitDialog, topicBean.Id, pageNo, pageSize);
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        ToolBarOptions options = new ToolBarOptions(R.string.topic_detail);
        setCustomToolBar(mDataBinding.customToolbar.toolbar, options);
        // 由于设置了fitsSystemWindows 需要减少padding 和 height
        mDataBinding.customToolbar.toolbar.setPadding(0,0,0,0);
        mDataBinding.customToolbar.toolbar.getLayoutParams().height = UIUtils.getDimensionPixelSize(R.dimen.action_bar_height);

        configTopicCountDetail();
        getData(true);
    }

    private void configTopicCountDetail() {
        if (topicBean == null) return;
        headerBinding.tvComment.setText("评论 " + topicBean.CommentCount);
        headerBinding.tvPraise.setText("赞 " + topicBean.LikeCount);
    }

    @Override
    protected TopicDetailPresenter getPresenter() {
        return new TopicDetailPresenter();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view == mDataBinding.btnSend) {
            if (mDataBinding.edtContent.length() == 0) {
                return;
            }
            String commentContent = mDataBinding.edtContent.getText().toString().trim();
            if (mPresenter != null) {
                mPresenter.commentTopic(replyToUser == null ? "" : replyToUser.ID, replyToTopicID, topicBean.Id, commentContent);
                mDataBinding.btnSend.setEnabled(false);
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            View view = getCurrentFocus();
            TDevice.hideSoftKeyboard(view);
        }
        return super.dispatchTouchEvent(event);
    }

    @Override
    public void configTopicCommentListData(PagerBean<CommentBean> data) {
        if (data == null) return;
        setLoadMoreLayout(data.list, data.totalPage);
    }

    @Override
    public void onCommentTopicCallback(boolean isSuccess, CommentBean data) {
        if (isSuccess) {
            if (data != null) {
                adapter.addData(0, data);
            }
            mDataBinding.edtContent.setText("");
            mDataBinding.edtContent.clearFocus();
        }
    }

    @Override
    public void onPraiseCommentCallback(boolean isSuccess, int position) {
        if (isSuccess) {
            CommentBean commentBean = adapter.getItem(position);
            commentBean.LikeCount += 1;
            commentBean.IsLike = 1;
            adapter.notifyItemChanged(position + adapter.getHeaderLayoutCount());
        }
    }

    @Override
    public void onCancelPraiseCommentCallback(boolean isSuccess, int position) {
        if (isSuccess) {
            CommentBean commentBean = adapter.getItem(position);
            commentBean.LikeCount -= 1;
            commentBean.IsLike = 0;
            adapter.notifyItemChanged(position + adapter.getHeaderLayoutCount());
        }
    }

    @Override
    public void onStarCommentCallback(boolean isSuccess, int position) {
        if (isSuccess) {
            CommentBean commentBean = adapter.getItem(position);
            commentBean.IsGood = 1;
            adapter.notifyItemChanged(position + adapter.getHeaderLayoutCount());
        }
    }

    @Override
    public void onCancelStarCommentCallback(boolean isSuccess, int position) {
        if (isSuccess) {
            CommentBean commentBean = adapter.getItem(position);
            commentBean.IsGood = 0;
            adapter.notifyItemChanged(position + adapter.getHeaderLayoutCount());
        }
    }
}
